package com.sl.au.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sl.au.entity.Attachment;
import com.sl.au.entity.Device;
import com.sl.au.entity.Module;
import com.sl.au.entity.ReplaceDevicePrice;
import com.sl.au.entity.ReplacementDevice;
import com.sl.au.entity.WholeSetDevice;
import com.sl.au.entity.WholeSetPrice;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.ExcelService;
import com.sl.au.service.ReplacementDeviceService;
import com.sl.au.service.WholeSetDeviceService;
import com.sl.au.service.WholeSetPriceService;

/**
 * 成套设备管理
 */
/**
 * @author asus1
 *
 */
@RestController
@RequestMapping(value = "/ui/wholeSetDevice")
public class WholeSetDeviceController extends BaseController {
	@Autowired
	WholeSetDeviceService wholeSetDeviceService;

	@Autowired
	WholeSetPriceService wholeSetPriceService;

	@Autowired
	AttachmentService attachmentService;
	
	@Autowired
	ExcelService excelService;

	

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = createLayoutView("wholeSetDevice/wholeSetDeviceIndex");
		String name="wholeSet"; 
        Module module = this.getPageModule(name);
		modelAndView.addObject("module", module);
		return modelAndView;
	}

	/**
	 * 获取页面数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if (key == null) {
			key = "";
		}
		key = key.replaceAll("\\s+", "");
		List<WholeSetDevice> sets = null;
		Long count = null;
		sets = wholeSetDeviceService.getPage(start, length, key, null, null);
		count = wholeSetDeviceService.getRepository().getCount(key);
		List<WholeSetDevice> newSets = new ArrayList<WholeSetDevice>();
		for (WholeSetDevice r : sets) {
			String parentId = r.getId();
			List<Attachment> a = attachmentService.getRepository().findByParentId(parentId);
			int num = a.size();
			r.setAttachNumber(num);
			newSets.add(r);
		}
		map.put("data", newSets);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/*
	 * 更新附件个数
	 */
	@RequestMapping(value = "updateAttachmentNum", method = RequestMethod.GET)
	public Map<String, Object> updateAttachmentNum(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String parentId = request.getParameter("deviceId");
		List<Attachment> a = attachmentService.getRepository().findByParentId(parentId);
		int num = a.size();
		WholeSetDevice device = wholeSetDeviceService.getRepository().findOne(parentId);
		device.setAttachNumber(num);
		wholeSetDeviceService.getRepository().save(device);
		return map;
	}

	
	/**验证型号唯一性
	 * @param request
	 * @return
	 */
	@RequestMapping(value="wholeTypeValidate",method=RequestMethod.GET)
	public Map<String,Object>codeValidate(HttpServletRequest request){
		Map<String, Object>map=new HashMap<String, Object>();
		String wholeSetDeviceId=request.getParameter("id");
		String type=request.getParameter("type");
		long count=0;
		if(wholeSetDeviceId==null||wholeSetDeviceId.equals("")){
			count=wholeSetDeviceService.getRepository().getReCount(type);
		}else{
			List<WholeSetDevice>wholeSetDevices=wholeSetDeviceService.getRepository().findByType(type);
			if(!wholeSetDevices.isEmpty()){
				if(!wholeSetDevices.get(0).getId().equals(wholeSetDeviceId)){
					count=wholeSetDevices.size();
				}
			}
//			WholeSetDevice wholeSetDevice=wholeSetDeviceService.getRepository().findOne(wholeSetDeviceId);
		}
		map.put("code",count);
		return map;
		
	}
	/*
	 * 添加成套设备并保存到成套价格本
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Map<String, Object> saveSet(HttpServletRequest request, @RequestBody WholeSetDevice set) {
		Map<String, Object> map = new HashMap<String, Object>();
		wholeSetDeviceService.getRepository().save(set);
		List<WholeSetPrice> p = new ArrayList<WholeSetPrice>();
		String type = set.getType();
		WholeSetPrice p1 = new WholeSetPrice();
		p1.setWholeSetDevice(set);
		p1.setEquipmentType(type);
		p1.setSuperior("成套处");
		p.add(p1);
		WholeSetPrice p2 = new WholeSetPrice();
		p2.setWholeSetDevice(set);
		p2.setEquipmentType(type);
		p2.setSuperior("外贸处");
		p.add(p2);
		WholeSetPrice p3 = new WholeSetPrice();
		p3.setWholeSetDevice(set);
		p3.setEquipmentType(type);
		p3.setSuperior("销售处");
		p.add(p3);
		WholeSetPrice p4 = new WholeSetPrice();
		p4.setWholeSetDevice(set);
		p4.setEquipmentType(type);
		p4.setSuperior("售后服务处");
		p.add(p4);
		wholeSetPriceService.getRepository().save(p);
		map.put("code", 0);
		return map;
	}

	/**
	 * 编辑保存一个成套设备
	 */
	@RequestMapping(method = RequestMethod.PATCH)
	public Map<String, Object> patchSet(@RequestBody WholeSetDevice set) {
		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		wholeSetDeviceService.patch(set);
		code = 0;
		map.put("code", code);
		return map;
	}

	/**
	 * 删除成套设备
	 * 
	 * @return
	 */
	@RequestMapping(value = "/delWholeSetDevice", method = RequestMethod.GET)
	public Map<String, Object> delWholeSetDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<WholeSetDevice> sets = new ArrayList<WholeSetDevice>();
		for (int i = 0; i < id.length; i++) {
			String setId = id[i];
			wholeSetPriceService.getRepository().deleteWholeSetPrice(setId);
			WholeSetDevice set = new WholeSetDevice();
			set.setId(setId);
			sets.add(set);
			List<Attachment> attachments = new ArrayList<Attachment>();
			attachments = attachmentService.getRepository().findByParentId(setId);
			attachmentService.getRepository().deleteInBatch(attachments);
		}
		wholeSetDeviceService.getRepository().deleteInBatch(sets);
		map.put("code", 0);
		return map;
	}

	/**
	 * EXCEL导入处理 *
	 */
	@RequestMapping(value = "/import", method = RequestMethod.POST)
	public Map<String, Object> importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		long count = -1;
		String saveFileName = attachmentService.upload(file);
		// 文件传后，再读取EXCEL写入数据库
		if (StringUtils.hasText(saveFileName)) {
			count = wholeSetDeviceService.importExcel(saveFileName);
			code = 0;
		}
		map.put("code", code);
		map.put("count", count);
		return map;
	}
	
	/*
	 * 查询导出excel，如果key='', 导出全部
	 */
	@RequestMapping(value = "export/{key}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> excelFile(@PathVariable String key,HttpServletRequest request) throws UnsupportedEncodingException {
		if(key.equals("null")) key="";
		List<WholeSetDevice> devices=wholeSetDeviceService.getPage(0, Integer.MAX_VALUE, key, null, null);
		return this.excelService.toExcel(devices, "成套设备.xlsx");
	}
	///导出选择项
	@RequestMapping(value = "/exportSelects/{key}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> exportSelects(@PathVariable String key, HttpServletRequest request)
					throws UnsupportedEncodingException {	
		String id[] = key.split(",");
		List<WholeSetDevice> devices = new ArrayList<WholeSetDevice>();
		for (int i = 0; i < id.length; i++) {
			String deviceId = id[i];
			WholeSetDevice d=wholeSetDeviceService.getRepository().findOne(deviceId);
			devices.add(d);
		}
		return this.excelService.toExcel(devices, "成套设备.xlsx");
	}
}
